<?php

namespace app\api\service\order\paysuccess\source;

use app\common\enum\settings\DeliveryTypeEnum;
use app\common\library\supply\Driver as SupplyDriver;
use app\common\service\order\OrderPrinterService;
use app\common\service\order\OrderCompleteService;
use app\common\enum\order\OrderTypeEnum;

/**
 * 普通订单支付成功后的回调
 */
class MasterPaySuccessService
{
    /**
     * 回调方法
     */
    public function onPaySuccess($order)
    {
        // 小票打印
        (new OrderPrinterService)->printTicket($order);
        // 如果是虚拟商品，则标记为已完成，无需发货
        if ($order['delivery_type']['value'] == DeliveryTypeEnum::NO_EXPRESS && $order['virtual_auto'] == 1) {
            $order->save([
                'delivery_status' => 20,
                'delivery_time' => time(),
                'receipt_status' => 20,
                'receipt_time' => time(),
                'order_status' => 30,
                'virtual_content' => $order['product'][0]['virtual_content'],
            ]);
            // 执行订单完成后的操作
            $OrderCompleteService = new OrderCompleteService(OrderTypeEnum::MASTER);
            $OrderCompleteService->complete([$order], $order['app_id']);
            $order->sendWxExpress('', '');
            // 给充值订单发货
            $this->justRecharge($order, $order["product"][0]["supply_no"], $order["username"], $order["order_no"]);
        }
        return true;
    }

    /**
     * 给用户发货
     */
    private function justRecharge($order, $commodityId, $username, $outOrderId)
    {
        $supplyDriver = new SupplyDriver([
            "default" => "Tao",
            "engine" => [
                "Tao" => []
            ]
        ]);
        $param = [
            "commodityId" => $commodityId,
            "username" => $username,
            "outOrderId" => $outOrderId,
            "time" => time(),
        ];
        $supplyDriver->sendData($param);
        try {
            $justRecharge = $supplyDriver->justRecharge();
            if (!$justRecharge) {
                $order->save([
                    "message" => $supplyDriver->getError()
                ]);
                return false;
            }
        } catch (\Exception $e) {
            mylog("justRecharge", ["错误代码" => $e->getCode(), "文件" => $e->getFile(), "行数" => $e->getLine(), "错误信息1" => $e->getMessage()]);
            return false;
        }
        $order->save([
            "desc" => "充值中，请稍后",
            "message" => "",
        ]);
        return true;
    }


}